package com.sy.olddriver.service.impl;

import com.alibaba.fastjson.JSON;
import com.sy.olddriver.constant.AppConstant;
import com.sy.olddriver.dao.CategoryDao;
import com.sy.olddriver.dao.impl.CategoryDaoImpl;
import com.sy.olddriver.dto.RootCategory;
import com.sy.olddriver.dto.SecondLevelCategory;
import com.sy.olddriver.entity.Category;
import com.sy.olddriver.service.CategoryService;
import com.sy.olddriver.utils.RedisUtils;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class CategoryServiceImpl implements CategoryService {
    private CategoryDao categoryDao = new CategoryDaoImpl();


    @Override
    public List<RootCategory> getCategoryInfo() {
        //先去缓存查询
        List<RootCategory> rootCategories = JSON.parseArray(RedisUtils.get(AppConstant.REDIS_CATEGORY_KEY), RootCategory.class);
        if (CollectionUtils.isEmpty(rootCategories)) {
            List<Category> firstLevelCategories = categoryDao.getSubCategoriesByParentId(0);
            rootCategories = new ArrayList<>();
            for (Category firstLevelCategory : firstLevelCategories) {
                RootCategory rootCategory = new RootCategory();
                //一级
                rootCategory.setSelf(firstLevelCategory);
                //二级
                List<Category> secondLevelCategories = categoryDao.getSubCategoriesByParentId(firstLevelCategory.getId());
                List<SecondLevelCategory> secondLevelCategoryList = new ArrayList<>();
                //三级
                for (Category secondLevelCategory : secondLevelCategories) {
                    SecondLevelCategory secondLevelCategory1 = new SecondLevelCategory();
                    secondLevelCategory1.setSelf(secondLevelCategory);
                    secondLevelCategory1.setThirdLevelCategoryList(categoryDao.getSubCategoriesByParentId(secondLevelCategory.getId()));
                    secondLevelCategoryList.add(secondLevelCategory1);
                }
                rootCategory.setSecondLevelCategoryList(secondLevelCategoryList);
                rootCategories.add(rootCategory);
            }
            RedisUtils.set(AppConstant.REDIS_CATEGORY_KEY, JSON.toJSONString(rootCategories));
        }
        return rootCategories;
    }
}
